package sub

import (
	"fmt"
	"quipus/cmd/qpc/sub"
	"quipus/internal/utils"
	v1pb "quipus/proto/gen/api/v1"
	cpb "quipus/proto/gen/common"

	"github.com/spf13/cobra"
)

var (
	filter   string
	limit    int32
	offset   int32
	savePath string
)

func init() {
	// sub.RegisterCommonFlags(tenantCmd)

	listCmd.PersistentFlags().StringVarP(&filter, "filter", "", "", "filter tenant")
	listCmd.PersistentFlags().Int32VarP(&limit, "limit", "", 100, "list limit")
	listCmd.PersistentFlags().Int32VarP(&offset, "offset", "", 0, "list offset")
	listCmd.PersistentFlags().Int32VarP(&subjectId, "subject", "s", 0, "list subject topics")
	listCmd.PersistentFlags().StringVarP(&savePath, "save-path", "p", "", "save topic to file")

	topicCmd.AddCommand(listCmd)
}

var listCmd = &cobra.Command{
	Use:   "list",
	Short: "Run cmd to list subjects",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := sub.NewGrpcConnect(sub.QpConfig.QPAddress)
		if e != nil {
			return e
		}

		if subjectId < 0 {
			return fmt.Errorf("subject id must be greater than 0")
		}

		qclient := v1pb.NewSubjectServiceClient(qconn)
		ctxWithToken := sub.NewCtxWithToken(sub.QpConfig.Token)
		pageToken := cpb.PageToken{Limit: 100, Offset: 0}
		subject := utils.BuildUrn(utils.SubjectUrnPrefix, subjectId)
		in := &v1pb.ListTopicsRequest{PageToken: &pageToken, Filter: filter, SubjectUrn: subject}
		rsp, err := qclient.ListTopics(ctxWithToken, in)
		if err != nil {
			return err
		}

		if len(savePath) > 0 {
			utils.WriteConfig(savePath, rsp.Topics)
		}

		fmt.Println("ID      URN              TITLE           CONTENT")
		if rsp != nil {
			for index, v := range rsp.Topics {
				p := v.Primary
				seq := index + 1
				fmt.Printf("%5d  %10s %10s    %12s   \n", seq, p.Urn, p.Title, p.Summary)
				units := v.Units
				for j, u := range units {
					s := fmt.Sprintf("%d-%d", seq, j+1)
					fmt.Printf("%5s  %10s %10s    %12s   \n", s, u.Urn, u.Title, u.Summary)
				}
			}
		}
		// fmt.Print(rsp)
		return nil
	},
}
